from django import http
from django.shortcuts import render
from django.views import View

from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE
from django.core.cache import cache
from . import constants


class AreasView(View):

    def get(self, request):
        area_id = request.GET.get('area_id')
        if area_id is None:
            # 先获取缓存，如果存在中不存在，再查询mysql并缓存
            result = cache.get('province_list')
            if result is None:
                provice_list_sql = Area.objects.filter(parent__isnull=True)
                provice_list = []
                for provice in provice_list_sql:
                    provice_list.append({
                        'id': provice.id,
                        'name': provice.name
                    })
                result = {
                    "code": "0",
                    "errmsg": "OK",
                    "province_list": provice_list
                }
                cache.set('province_list', result, constants.AREA_CACHE_EXPIRES)
            return http.JsonResponse(result)
        else:
            result = cache.get('area_' + area_id)
            if result is None:
                try:
                    parent_model = Area.objects.get(id=area_id)  # 查询市或区的父级
                except Exception as e:
                    return http.JsonResponse({
                        'code': RETCODE.PARAMERR,
                        'errmsg':'市或区参数有误'
                    }
                    )
                cities_list_sql = parent_model.subs.all()
                cities_list = []
                for city in cities_list_sql:
                    cities_list.append(
                        {
                            'id': city.id,
                            'name': city.name
                        }
                    )
                result = {
                    'code': '0',
                    'errmsg': 'OK',
                    "sub_data": {
                        'id': parent_model.id,
                        'name': parent_model.name,
                        'subs': cities_list
                    }
                }
                cache.set('area_' + area_id, result, constants.AREA_CACHE_EXPIRES)
            return http.JsonResponse(
                    result
                )

